package com.cacho.s2b.lesson.grammar.func;

import com.cacho.s2b.lesson.security.Activation;
import com.cacho.s2b.lesson.vo.ApiTestInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

import static com.cacho.s2b.lesson.security.JWTCustom.generateJWT;
import static com.cacho.s2b.lesson.security.JwtNimbusJose.nimbusJoseJwt;

@Slf4j
public class GrammarFuncJWT implements GrammarFunc {
    @Override
    public String getString(ApiTestInfo testInfo, String[] parts, int len) {
        int paramSize = parts.length;
        if (paramSize < 1) {
            return null;
        }
        // groupId 必填
        String groupId = parts[0];
        String privateKey = Activation.loadActivationProps().getProperty(groupId + "_PrivateKey");
        // 如果参数>1,第二个取传入的，否则取默认30
        long expirySecs = paramSize > 1 ? Integer.parseInt(parts[1]) : 30;
        String alg = paramSize > 2 ? parts[2] : "RS256";
        Map<String, String> payload = testInfo.getLastStepInfo().getJwtDataMap();
        String jwtToken = "";
        try {
            jwtToken = nimbusJoseJwt(expirySecs, payload, privateKey, alg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jwtToken;
    }
}
